'use strict';

var http = require('http'),
  path = require('path'),
  express = require('express'),
  bodyParser = require('body-parser'),
  session = require('express-session'),
  hbs = require('express-hbs'),
  logger = require('./app/helper/logger'),
  controllers = require('./app/controllers'),
  util = require('./app/helper/util'),
  CONSTS = require('./conf/const'),
  util = require('./app/helper/util'),
  errCode = require('./conf/errorCode');

const DEFAULT_PORT = 1101;
const TAG = 'APP';
//var PORT = process.argv[2] || DEFAULT_PORT;
var PORT = DEFAULT_PORT;

var app = express();

// view engine setup
app.engine(
  'hbs',
  hbs.express3({
    viewsDir: path.join(__dirname, 'app/views'),
    //partialsDir: path.join(__dirname, 'app/views/partials'),
    //layoutsDir: path.join(__dirname, 'app/views/layouts'),
  }),
);
// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'hbs');
//app.use(express.static(path.join(__dirname, './public')));
app.use(bodyParser.json()); // for parsing application/json
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
); // for parsing application/x-www-form-urlencoded

app.use(
  session({
    name: 'xiaop',
    secret: 'biz-fe',
    maxAge: 30 * 60 * 1000,
    resave: false,
    saveUninitialized: false,
  }),
);
var tagLogger = new logger.TagLogger(TAG);
var server = http.createServer(app);
server.on('connection', socket => {
  socket.setTimeout(100 * 1000);
});

app.use(function(req, res, next) {
  let timeId = res.setTimeout(CONSTS.MAX_CONNECT_TIMEOUT, function() {
    clearTimeout(timeId);
    tagLogger.error(`request Timout,request url is ${req.originalUrl}`);
  });
  next();
});

app.use('/+nnc', controllers.api);
app.use('/+nnc/auth', controllers.authRouter);
app.use('/+nnc/common', controllers.commonRouter);
app.use('/+nnc/comment', controllers.commentRouter);
app.use('/+nnc/post', controllers.postRouter);
app.use('/+nnc/vehicle', controllers.vehicleRouter);
app.use('/+nnc/spider', controllers.spiderRouter);
app.use('/+nnc/poll', controllers.pollRouter);
app.use('/+nnc/operate', controllers.dataRouter);
app.use('/+nnc/user', controllers.userRouter);
app.use('/+nnc/report', controllers.reportRouter);
app.use('/', controllers.root);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).end('404');
});

server.listen(PORT, () => {
  tagLogger.info('listening on ' + PORT);
});

process.on('uncaughtException', function(err) {
  tagLogger.error('uncaughtException' + err.stack);
});
